package com.example.pdfSplice.controller;

import com.example.pdfSplice.model.PdfMergeRequest;
import com.example.pdfSplice.model.PdfPageInfo;
import com.example.pdfSplice.service.PdfService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * PDF处理控制器
 */
@RestController
@RequestMapping("/api/pdf")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class PdfController {
    
    private final PdfService pdfService;
    
    /**
     * 上传PDF文件并解析页面信息
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadPdf(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (!file.getOriginalFilename().toLowerCase().endsWith(".pdf")) {
                response.put("success", false);
                response.put("message", "只支持PDF文件");
                return ResponseEntity.badRequest().body(response);
            }
            
            List<PdfPageInfo> pageInfos = pdfService.uploadPdf(file);
            
            response.put("success", true);
            response.put("message", "文件上传成功");
            response.put("data", pageInfos);
            
            return ResponseEntity.ok(response);
            
        } catch (IOException e) {
            log.error("上传PDF文件失败: {}", e.getMessage(), e);
            response.put("success", false);
            response.put("message", "文件处理失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 拼接PDF
     */
    @PostMapping("/merge")
    public ResponseEntity<?> mergePdf(@RequestBody PdfMergeRequest request) {
        try {
            if (request.getTargetPages() == null || request.getTargetPages().isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "目标页面配置不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            byte[] mergedPdf = pdfService.mergePdf(request);
            
            String fileName = request.getOutputFileName();
            if (fileName == null || fileName.trim().isEmpty()) {
                fileName = "merged.pdf";
            }
            if (!fileName.toLowerCase().endsWith(".pdf")) {
                fileName += ".pdf";
            }
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentLength(mergedPdf.length);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(mergedPdf);
                    
        } catch (Exception e) {
            log.error("拼接PDF失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "拼接失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 清理指定文件的缓存
     */
    @DeleteMapping("/cache/{fileId}")
    public ResponseEntity<Map<String, Object>> clearCache(@PathVariable String fileId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            pdfService.clearCache(fileId);
            response.put("success", true);
            response.put("message", "缓存清理成功");
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("清理缓存失败: {}", e.getMessage(), e);
            response.put("success", false);
            response.put("message", "清理缓存失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 清理所有缓存
     */
    @DeleteMapping("/cache")
    public ResponseEntity<Map<String, Object>> clearAllCache() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            pdfService.clearAllCache();
            response.put("success", true);
            response.put("message", "所有缓存清理成功");
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("清理所有缓存失败: {}", e.getMessage(), e);
            response.put("success", false);
            response.put("message", "清理缓存失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}
